#include "utils/socket.h"
#include <iostream>

using namespace cox;

void testTcpServer() {
	// 创建TCP socket
	Socket serverSocket(Socket::TCP);

	if (serverSocket.getFd() < 0) {
		std::cerr << "创建服务器Socket失败，错误码：" << serverSocket.getError() << std::endl;
		return;
	}

	// 设置地址复用（避免端口占用问题）
	if (!serverSocket.setReuseAddr(true)) {
		std::cerr << "设置地址复用失败" << std::endl;
		return;
	}

	// 绑定地址（本地8080端口）
	NetAddr serverAddr("0.0.0.0", 8080);
	if (!serverSocket.bind(serverAddr)) {
		std::cerr << "绑定地址失败，错误码：" << serverSocket.getError() << std::endl;
		return;
	}

	// 开始监听（最大等待队列10）
	if (!serverSocket.listen(10)) {
		std::cerr << "监听失败，错误码：" << serverSocket.getError() << std::endl;
		return;
	}
	std::cout << "TCP服务器启动，监听 " << serverAddr.host << ":" << serverAddr.port << std::endl;

	// 用select处理新连接
	std::vector<Socket *> readVec;
	readVec.push_back(&serverSocket);

	while (true) {
		// 等待可读事件（超时1秒）
		int ret = Socket::select(&readVec, nullptr, nullptr, TimeVal(1, 0));
		if (ret < 0) {
			std::cerr << "select错误" << std::endl;
			break;
		}

		// 处理就绪的socket
		for (Socket *sock: readVec) {
			if (sock == &serverSocket) {
				// 接受新连接
				auto clientSocket = serverSocket.accept();
				if (clientSocket) {
					std::cout << "新客户端连接：" << clientSocket->getAddr().host << ":" << clientSocket->getAddr().port << std::endl;
					// 向客户端发送欢迎消息
					const char *msg = "欢迎连接TCP服务器！";
					clientSocket->send(msg, strlen(msg));

					// 读取客户端数据
					char      buf[1024] = {0};
					long long recvLen   = clientSocket->recv(buf, 1023);
					if (recvLen > 0) {
						std::cout << "收到客户端数据：" << buf << std::endl;
					}
				}
			}
		}
		readVec.clear();
		readVec.push_back(&serverSocket); // 重新添加监听socket
	}
}

// 编译：g++ -std=c++11 -o socket_server socket_server.cpp SocketAdapter.cpp  TimeAdapter.cpp
int main() {
	testTcpServer();
	return 0;
}